<?php 
/**
 * Класс, который реализовует базовые настройки PHP-Ext
 *
 */

class FRM_View_Ext_Form_Template_Abstract
{
	/**
	 * Enter description here...
	 *
	 * @var array
	 */
	protected $zones = array();

	protected static $controller;
	protected static $module;

	/**
	 * Enter description here...
	 *
	 * @var PhpExt_Data_JsonReader
	 */
	protected $reader;

	/**
	 * Enter description here...
	 *
	 * @var PhpExt_Form_FormPanel
	 */
	protected  $form;

	/**
	 * Enter description here...
	 *
	 * @var string
	 */
	protected $varName;

	/**
	 * Enter description here...
	 *
	 * @var boolean
	 */
	protected $needUploader = false;

	/**
	 * Enter description here...
	 *
	 * @var array
	 */
	protected $config;
	
	protected $langs= array();

	protected $uploaders= array();

	static function setController($controller){
		self::$controller = $controller;
	}

	public function __construct($varName, $langs = array(), $config = array()){

		$this->langs = $langs;

		$this->varName = $varName;
		$this->config = $config;

		$this->reader = new PhpExt_Data_JsonReader();
		$this->reader ->setSuccessProperty("success");
		$this->reader ->setRoot("data");
		
		$this->form = new PhpExt_Form_FormPanel();
		$this->form -> setLabelWidth($config['labelWidth'])
		-> setDefaults(new PhpExt_Config_ConfigObject(array("bodyStyle"=>"padding:5px 10px 10px 10px;")))
		-> setCssStyle("padding:10px;")
		-> setAutoHeight($config['autoHeight'])
		-> setLabelAlign($config['labelAlign'])
		-> setBorder($config['border'])
		-> setButtonAlign($config['buttonAlign']);


		$this->init();
	}

	protected function init(){

	}

	/**
	 * Enter description here...
	 *
	 * @param int $zone
	 * @param array $field
	 */
	public function addField($field){

		$zone=	(isset($field['zone']))?$field['zone']:0;

		if(!isset($this->zones[$zone])){
			return ;
		}
		$type=	(isset($field['type']))?$field['type']:"";

		$anchor=(isset($field['anchor']))?$field['anchor']:null;
		$name=	(isset($field['name']))?$field['name']:'';
		$map=	(isset($field['map']))?$field['map']:$name;
		$useRvOptions=	(isset($field['useRvOptions']))?$field['useRvOptions']:false;

		$label=	(isset($field['label']))?$field['label']:null;
		$vtype=	(isset($field['vtype']))?$field['vtype']:null;
		$vtext=	(isset($field['vtext']))?$field['vtext']:null;
		$width=	(isset($field['width']))?$field['width']:null;
		$height=	(isset($field['height']))?$field['height']:null;
		$labelWidth=	(isset($field['labelWidth']))?$field['labelWidth']:null;
		$labelSeparator=	(isset($field['labelSeparator']))?$field['labelSeparator']:":";
		$value=	(isset($field['value']))?$field['value']:null;
		$allowBlank=(isset($field['allowBlank']))?$field['allowBlank']:true;
		$listeners=(isset($field['listeners']) && is_array($field['listeners']))?$field['listeners']:null;

		switch ($type) {
			case "TextField":
				$id=	(isset($field['id']))?$field['id']:$name;
				$maskReg =	(isset($field['maskReg']))?$field['maskReg']:null;
				$item = PhpExt_Form_TextField::createTextField($name,$label,$id,$vtype);
				$item->setWidth($width);
				$item->setAllowBlank($allowBlank);
				$item->setAutoHeight(false);
				$item->setAnchor($anchor);
				$item->setValue($value);
				$item->setVType($vtype);
				if ($useRvOptions)
				{
					$item->setPlugins(PhpExt_Javascript::inlineStm('[Ext.ux.plugins.RemoteValidator]'));					
					$item->setRvOptions(PhpExt_Javascript::inlineStm("rvOptions"));					
				}
				$item->setVTypeText($vtext);
				if (!is_null($maskReg))
				{
					$item->setMaskRegEx(PhpExt_Javascript::inlineStm($maskReg));
				}
				$item->setLabelSeparator($labelSeparator);
				if (!is_null($labelWidth))
				{
					//	$item->setLabelCssStyle("width:".$labelWidth."px");
				}
				break;
			case "Hidden":
				$id=	(isset($field['id']))?$field['id']:$name;

				$item = PhpExt_Form_Hidden::createHidden($name,null);
				$item->setWidth($width);
				$item->setValue($value);
				$item->setId("hidden_".$name);
				//$field->setAllowBlank($allowBlank);
				break;
			case "Checkbox":
				$id=	(isset($field['id']))?$field['id']:$name;

				$item = PhpExt_Form_Checkbox::createCheckbox($name,$label);
				$item->setWidth($width);
				$item->setValue($value)
				->setCssStyle("margin-top:3px;");
				if (!is_null($labelWidth))
				{
					//	$item->setLabelCssStyle("width:".$labelWidth."px");
				}
				$item->setLabelSeparator($labelSeparator);
				//$field->setAllowBlank($allowBlank);
				break;
			case "Combobox":
				$id=	(isset($field['id']))?$field['id']:null;
				$http=	(isset($field['http']))?$field['http']:false;
				$hiddenName=	(isset($field['hiddenName']))?$field['hiddenName']:$name;
				$stListeners=(isset($field['stListeners']) && is_array($field['stListeners']))?$field['stListeners']:null;

				
				if ($http)
				{
					$url=	(isset($field['url']))?$field['url']:false;
					$reader = new PhpExt_Data_ArrayReader();
					$reader		-> addField(new PhpExt_Data_FieldConfigObject('key'));
					$reader		-> addField(new PhpExt_Data_FieldConfigObject('value'));

					$http = new PhpExt_Data_HttpProxy();
					$http -> setUrl($url);
					
					$store = new PhpExt_Data_Store();
					$store -> setProxy($http)
					-> setReader($reader);
					if (!is_null($stListeners))
					{
						foreach ($stListeners as $k=>$v)
						{
							$store->attachListener($k,new PhpExt_Listener(PhpExt_Javascript::inlineStm($v)));
						}
					}
				}else 
				{
					$store = new PhpExt_Data_SimpleStore();
					$store->addField('key');	
					$store->addField('value');
					if (isset($field['data']) && is_array($field['data']))
					{
						$store -> setData($field['data']);
					}
				}
				
				
				$emptyText   =(isset($field['emptyText']))?$field['emptyText']:'';
				
				$item = PhpExt_Form_ComboBox::createComboBox('combo-'.$name,$label,$id);
				if (!is_null($labelWidth))
				{
					//	$item->setCssStyle("margin-left:".$labelWidth."px");
				}
				$item->setLabelSeparator($labelSeparator);
				$item->setStore($store);
				$item->setEditable(false);
				if (!is_null($id))
				{
					$item->setId('combo-'.$id);
				}
				$item->setHiddenName($hiddenName);
				$item->setName($name);
				$item->setValueField('key');
				$item->setAllowBlank($allowBlank);
				$item->setDisplayField('value');
				$item->setMode("local");
				$item->setWidth($width);
				$item->setTriggerAction('all');
				//$item->setForceSelection(true);
				unset($store);
				break;
			case "TextArea":
				$id=	(isset($field['id']))?$field['id']:$name;

				$item = PhpExt_Form_TextArea::createTextArea($name,$label);
				$item->setWidth($width);
				$item->setAllowBlank($allowBlank);
				$item->setAnchor($anchor);
				$item->setValue($value);
				$item->setLabelSeparator($labelSeparator);
				if (!is_null($labelWidth))
				{
					$item->setLabelCssStyle("width:".$labelWidth."px");
				}
				break;
			case "HtmlEditor":
				$id=	(isset($field['id']))?$field['id']:$name;

				$item = PhpExt_Form_HtmlEditor::createHtmlEditor($name,$label);
				$item->setWidth($width);
				$item->setValue($value);
				//$item->setHeight(100);
				$item->setAutoHeight(false);
				$item->setLabelSeparator($labelSeparator);
				if (!is_null($labelWidth))
				{
					$item->setLabelCssStyle("width:".$labelWidth."px");
				}
				break;
			case "TextButton":
				$id=	(isset($field['id']))?$field['id']:$name;

				$text=	(isset($field['text']))?$field['text']:'';
				$handler=	(isset($field['handler']))?$field['handler']:'';
				$item = PhpExt_Button::createTextButton($text,PhpExt_Javascript::inlineStm($handler));
				break;
			case "Uploader":
				$id=	(isset($field['id']))?$field['id']:$name;

				$maxCount =	(isset($field['maxCount']))?$field['maxCount']:0;
				$item = new PhpExt_Form_FieldSet();
				$item -> setCheckboxToggle(true)
				-> setTitle($label)
				-> setAutoHeight(true)
				-> setCollapsed(true);
				//$this->needUploader = true;
				$item2 = new PhpExt_Panel();
				$item2 ->setBorder(false);
				$item2 -> setId("uploader-".$name);
				$item -> addItem($item2);
				$this->uploaders[$name]= $maxCount;
				break;
			case "Galery":
				$id=(isset($field['id']))?$field['id']:$name;
				$url=(isset($field['url']))?$field['url']:null;
				$id_tf=(isset($field['id_tf']))?$field['id_tf']:null;
				$tplGalery=(isset($field['tplGalery']))?$field['tplGalery']:null;
				//$fields=(isset($field['fields']) && is_array($field['fields']))?$field['fields']:array();


				$reader = new PhpExt_Data_JsonReader();
				$reader		-> setRoot('images');
				$reader		-> setId('id');
				$reader		-> addField(new PhpExt_Data_FieldConfigObject('id','id'));
				$reader		-> addField(new PhpExt_Data_FieldConfigObject('photo','photo'));
				$reader		-> addField(new PhpExt_Data_FieldConfigObject('is_main','is_main'));

				$http = new PhpExt_Data_HttpProxy();
				$http -> setUrl($url);

				$imagesStore = new PhpExt_Data_Store();
				$imagesStore -> setProxy($http)
				-> setBaseParams(array('id_tf'=>$id_tf))
				-> setReader($reader);

				$dataViev = new PhpExt_DataView("div.thumb-wrap");
				$dataViev ->setStore($imagesStore)
							->setTemplate($tplGalery)
							->setSimpleSelect(true)
							->setLoadingText("Загрузка...")
							->setSingleSelect(true)
							->setSelectedCssClass("x-view-selected")
							->setOverCssClass("x-view-over")
							->setEmptyText("Изображения отсутствуют")
				/* ->setPlugins(PhpExt_Javascript::inlineStm("[
				new Ext.DataView.DragSelector(),
				new Ext.DataView.LabelEditor({dataIndex: 'name'})
				]"))*/;
				//Top Toolbar
				$removeHandler = new PhpExt_Handler();
				$removeHandler = PhpExt_Javascript::inlineStm("function() {
			      var m = Ext.getCmp('galery').items.get(0).getSelectedRecords();
			      if(m.length > 0) {
			         Ext.MessageBox.confirm('Информация', 'Вы действительно хотите удалить выбранный элемент?', function(btn) {
			            if(btn == 'yes') {
			                m[0].store.remove(m[0]);
			                var strC = new Ext.data.Store( {
			                  autoLoad : false, baseParams : {'id_offer':m[0].store.baseParams.id}
			                  , failure : function(form, action) {
			                     Ext.MessageBox.alert('Ошибка', action.result.msg); }, success: function (){ alert('fdf');m[0].store.load();}
			                  , proxy : new Ext.data.HttpProxy( {
			                     url : '/".self::$module."/gallery/delete/'+m[0].get('id')+'/'}
			                  ), remoteSort : false}
			               ); strC.load({callback:function (){ m[0].store.load();}});}
			            }
			         );
			         }
			      else {
			         Ext.MessageBox.alert('Информация', 'Нет выбраных элементов');
			         }
			      }");
				$upHandler = new PhpExt_Handler();
				$upHandler = PhpExt_Javascript::inlineStm("function() {
			      var m = Ext.getCmp('galery').items.get(0).getSelectedRecords();
			      if(m.length > 0) {
			               var strC = new Ext.data.Store( {
			                  autoLoad : false, baseParams : {'id_offer':m[0].store.baseParams.id}
			                  , failure : function(form, action) {
			                     Ext.MessageBox.alert('Ошибка', action.result.msg); }, success: function (){ alert('fdf');m[0].store.load();}
			                  , proxy : new Ext.data.HttpProxy( {
			                     url : '/".self::$module."/gallery/up/'+m[0].get('id')+'/'}
			                  ), remoteSort : false}
			               ); strC.load({callback:function (){ m[0].store.load();}});
			         }
			      else {
			         Ext.MessageBox.alert('Информация', 'Нет выбраных элементов');
			         }
			      }");		
				$downHandler = new PhpExt_Handler();
				$downHandler = PhpExt_Javascript::inlineStm("function() {
			      var m = Ext.getCmp('galery').items.get(0).getSelectedRecords();
			      if(m.length > 0) {
			      
			               var strC = new Ext.data.Store( {
			                  autoLoad : false, baseParams : {'id_offer':m[0].store.baseParams.id}
			                  , failure : function(form, action) {
			                     Ext.MessageBox.alert('Ошибка', action.result.msg); }
			                  , proxy : new Ext.data.HttpProxy( {
			                     url : '/".self::$module."/gallery/down/'+m[0].get('id')+'/'}
			                  ), remoteSort : false}
			               ); strC.load({callback:function (){ m[0].store.load();}});
			         }
			      else {
			         Ext.MessageBox.alert('Информация', 'Нет выбраных элементов');
			         }
			      }");	
				$mainHandler = new PhpExt_Handler();
				$mainHandler = PhpExt_Javascript::inlineStm("function() {
			      var m = Ext.getCmp('galery').items.get(0).getSelectedRecords();
			      if(m.length > 0) {
			               var strC = new Ext.data.Store( {
			                  autoLoad : false, baseParams : {'id_offer':m[0].store.baseParams.id}
			                  , failure : function(form, action) {
			                     Ext.MessageBox.alert('Ошибка', action.result.msg); }, success: function (){ alert('fdf');m[0].store.load();}
			                  , proxy : new Ext.data.HttpProxy( {
			                     url : '/".self::$module."/gallery/main/'+m[0].get('id')+'/'}
			                  ), remoteSort : false,listeners: {load: function (){ m[0].store.load();}}}
			               ); strC.load({callback:function (){ m[0].store.load();}});
			         }
			      else {
			         Ext.MessageBox.alert('Информация', 'Нет выбраных элементов');
			         }
			      }");	
				$tbar = new PhpExt_Toolbar_Toolbar();
				$tbar ->addButton("up","Вверх",TEMP_JS."/ext1/resources/images/default/grid/remove.gif",$upHandler);
				$tbar ->addButton("down","Вниз",TEMP_JS."/ext1/resources/images/default/grid/remove.gif",$downHandler);
				$tbar ->addButton("main","Сделать главным",TEMP_JS."/ext1/resources/images/default/grid/remove.gif",$mainHandler);
				$tbar ->addButton("remove","Удалить",TEMP_JS."/ext/resources/images/default/grid/remove.gif",$removeHandler);

				$item = new PhpExt_Panel();
				$item->setLayout(new PhpExt_Layout_FitLayout())
				->setTopToolbar($tbar)
				->setId($id)
				->setAutoScroll(true);
				$item->setAutoHeight(true);
				$item->setHeight($height);
				$item->setWidth($width);
				$item->setCssStyle("padding-bottom:10px;");

				$item->addItem($dataViev);
				break;
			default:
				break;
		}
		if (!is_null($listeners))
		{
			foreach ($listeners as $k=>$v)
			{
				$item->attachListener($k,new PhpExt_Listener(PhpExt_Javascript::inlineStm($v)));
			}
		}
		if(isset($item) && !is_null($item)){
			$this->zones[$zone]->addItem($item);
			$reader = new PhpExt_Data_FieldConfigObject($name, $map);
			$this->reader->addField($reader);
		}
	}

	public function render(){
		$this->form->setReader($this->reader);
		$this->form->setAutoScroll(true);
		$this->form->setHeight(300);
	/*	$this->form->attachListener('show',new PhpExt_Listener(PhpExt_Javascript::inlineStm("
		function()
		{

			
		}")));*/
		// Ext.OnReady -----------------------
		PhpExt_Ext::addOnReady(
		$this->form->getJavascript(false,$this->varName),
		PhpExt_Javascript::inlineStm("editForm.on('actioncomplete',
		function()
		{
				var combo = $this->varName.findByType('combo');
				for (var i=0; i<combo.length;i++)
				{
					combo[i].show();
				}
		})")
		);
		if (count($this->uploaders)){
			$i = 0;
			PhpExt_Ext::addOnReady(
			PhpExt_Javascript::inlineStm("var uploader = new Array();
					function submitAfterUpload(){
            	  		if(uploader_started == uploader_finished){
            	  		editForm.form.submit( {
                  waitMsg : 'Подождите...', url : '/".self::$module."/".self::$controller."/save', failure : function(form, action) {
                     Ext.MessageBox.alert('Ошибка', action.result.msg); }
                  , success : function(form, action) {
                     Ext.MessageBox.alert('Информация', 'Данные успешно сохранены'); editWindow.hide(); store.load( {
                        params : {
                           start : 0, limit : 25}
                        }
                     ); }
                  }
               ); 
				Ext.Msg.hide();
                }
            	  		
					}")
					);
					PhpExt_Ext::addOnReady(
					PhpExt_Javascript::inlineStm("var uploader_finished = 0;var uploader_started = 0;")
					);
					foreach ($this->uploaders as $k=>$v)
					{
						PhpExt_Ext::addOnReady(
						PhpExt_Javascript::inlineStm("String.prototype.trim = function() {
				return this.replace(/^\s+|\s+$/g,\"\");
			}
			uploader[$i] = new Ext.ux.SwfUploadPanel({
				displayTitle: false
				, id : 'uploaders[$k]'
				, height: 140
				, upload_url: '/".self::$module."/".self::$controller."/upload'
				, flash_url: \"".BASE_URL."js/swfUpload/swfupload_f9.swf\"
				, single_select: true // Select only one file from the FileDialog
				, file_post_name: '$k'
				, single_file_select: true // Set to true if you only want to select one file from the FileDialog.
				, confirm_delete: false // This will prompt for removing files from queue.
				, remove_completed: true // Remove file from grid after uploaded.
				, max_count: ".$v." 
				, post_params: {PHPSESSIDX: '".Zend_Session::getId()."'}
			});

			uploader[$i].on('swfUploadLoaded', function() { 
			});
			
			uploader[$i].on('fileUploadComplete', function(panel, file, response) {
			});
			
			uploader[$i].on('queueUploadComplete', function() {
			editForm.add(new Ext.form.Field({
            autoCreate : {tag:'input', type: 'hidden', name: '$k',  id: 'uploader-$k', value:0, width: 0},
            labelSeparator:''
        }))
        editForm.doLayout();
				uploader_finished++;
				submitAfterUpload();
			});
")//,
	//					PhpExt_Javascript::inlineStm("Ext.getCmp('uploader-$k').add(uploader[$i]);")

						);
						$i++;
					}
		}
		return $this->form;
	}
}